package service.impl;

import common.impl.exception.ServiceException;

import model.MSelection;
import net.sf.json.JSONObject;
import service.interf.ISelection;
import dao.interf.ISelectionDao;
import dao.pojo.Selection;



public class SelectionImpl implements ISelection{
	private ISelectionDao selectionDao;

	public void setselectionDao(ISelectionDao selectionDao) {
		this.selectionDao = selectionDao;
	}

	@Override
	public String add(MSelection model) {
		Selection selection = new Selection();

		selection.setSelectionDirections(model.getSelectionDirections());
		selection.setSelectionKeys(model.getSelectionKeys());
		selection.setSelectionPassge(model.getSelectionPassge());
		selection.setSelections(model.getSelections());

		return selectionDao.add(selection);
	}

	@Override
	public String getById(MSelection model) {
		Selection selection = selectionDao.getById(model.getSelectionId());
		if(null == selection) {
			throw new ServiceException("ERR-0141");
		}

		return createSelectionObj(selection).toString();
	}

	@Override
	public String deleteById(Integer id) {
		selectionDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MSelection model) {
		Selection selection = selectionDao.getById(model.getSelectionId());
		if (null == selection) {
			throw new ServiceException("ERR-0141");
		}

		selection.setSelectionDirections(model.getSelectionDirections());
		selection.setSelectionKeys(model.getSelectionKeys());
		selection.setSelectionPassge(model.getSelectionPassge());
		selection.setSelections(model.getSelections());

		selectionDao.edit(selection);
		return "1";
	}

	public JSONObject createSelectionObj(Selection selection) {
		JSONObject obj = new JSONObject();

		obj.put("selectionId", selection.getSelectionId());	
		obj.put("selectionDirections", selection.getSelectionDirections());
		obj.put("selectionKeys", selection.getSelectionKeys());
		obj.put("selectionPassge", selection.getSelectionPassge());
		obj.put("selections", selection.getSelections());

		return obj;
	}


}
